package middleware

import (
	"github.com/gin-gonic/gin"
	"log"
	"lover/model/back/entity"
	"lover/model/constant"
	"lover/utilx/authx"
	"lover/utilx/ginx"
	"net/http"
)

type SkipFun = func(ctx *gin.Context) bool

func JWT(skips ...SkipFun) gin.HandlerFunc {
	return func(c *gin.Context) {
		for _, skip := range skips {
			if skip(c) {
				c.Next()
				return
			}
		}
		token := c.GetHeader(constant.Authorization)
		if len(token) > 0 {
			log.Println("token", token)
			claims, err := authx.ParseWithClaims[entity.CloudUser]([]byte("asd"), token)
			if err != nil {
				ginx.AbortErrWith(c, 401, "err", err.Error())
				return
			}
			c.Set(constant.UserInfo, claims.Data)
			c.Set(constant.Admin, false)
			c.Next()
			return
		}
		ginx.AbortErrWith(c, 401, "no login info", nil)
		return
	}
}

func AuthPermission(skips ...SkipFun) gin.HandlerFunc {
	return func(c *gin.Context) {
		for _, skip := range skips {
			if skip(c) {
				c.Next()
				return
			}
		}
		if c.GetBool(constant.Admin) {
			c.Next()
			return
		}
		if !c.GetBool(constant.Admin) && c.Request.Method == http.MethodGet {
			c.Next()
			return
		}
		ginx.AbortErrWith(c, 401, "no permission", nil)
		return
	}
}
